package com.driving.code.controller;


import com.driving.code.entity.TUser;
import com.driving.code.service.TUserService;
import com.driving.code.utils.MyUsernamePasswordToken;
import com.driving.code.utils.RandomStringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author molie
 * @since 2022-02-10
 */
@RestController
@RequestMapping("user")
public class TUserController {
    @Resource
    private TUserService tUserService;

    /**
     * 注册方法
     * @param tUser
     * @return
     */
    @RequestMapping("register")
    public String register(TUser tUser){
        String string = RandomStringUtils.getString(5);
        tUser.setUserSalt(string);
        Md5Hash md5Hash = new Md5Hash(tUser.getUserPassword(),string,1024);
        String password = md5Hash.toHex();
        tUser.setUserPassword(password);
        boolean save = tUserService.save(tUser);
        if (save){
            return "1";
        }
        return "0";
    }

    /**
     * 登录方法
     * @param userAccount
     * @param password
     * @return
     */
    @RequestMapping("login")
    public String login(String userAccount,String password){
        MyUsernamePasswordToken token = new MyUsernamePasswordToken(userAccount,password,"UserRealm");
        Subject subject = SecurityUtils.getSubject();
        subject.login(token);
        return "0";
    }

    /**
     * 退出方法
     * @return
     */
    @RequestMapping("logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "1";
    }

    /**
     * 修改照片
     * @return
     */
    @RequestMapping("updateImage")
    public void updateImage(@RequestBody TUser user_post, HttpSession session){
        TUser user = (TUser) session.getAttribute("user");
        user.setUserImage(user_post.getUserImage());
        tUserService.updateById(user);
        session.setAttribute("user",user);
    }

    /**
     * 获取我的个人信息
     * @return
     */
    @RequestMapping("getMyInformation")
    @ResponseBody
    public TUser getMyInformation(HttpSession session){
        TUser user = (TUser) session.getAttribute("user");
        TUser tUser = tUserService.getById(user.getUserId());
        return tUser;
    }
}

